#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <unistd.h>
#include <pthread.h>
#include <memory>
#include <vector>
#include "Mutex.hpp"
using namespace std;   
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
int tickets=10000; 
void* getTicket(void* args)
{ 
    string threadName=static_cast<const char*>(args);
    while(1)
    {
        {   //RAII风格的加锁
            LockGuard lockgrand(&lock);//在作用域中自动加锁
            if(tickets>0)
            {
                usleep(1000);
                std::cout<<threadName<<"正在进行抢票"<<tickets<<std::endl;
                --tickets;
            }
            else
            {
                break;
            }
        }//出了作用域自动解锁

        //usleep(1000);
    }
    return nullptr;
}

int main()
{
    pthread_t t1, t2, t3, t4;
    pthread_create(&t1, nullptr, getTicket, (void *)"thread 1");
    pthread_create(&t2, nullptr, getTicket, (void *)"thread 2");
    pthread_create(&t3, nullptr, getTicket, (void *)"thread 3");
    pthread_create(&t4, nullptr, getTicket, (void *)"thread 4");

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);
    return 0; 
}